#!/bin/bash

function getSMARTValue(){
	grepKey=$1
	grepFile=$2

	grep "${grepKey}" $grepFile |head -n 1 |awk '{print $10}'| awk '{gsub(/^\s+|\s+$/, "");print}'
}

## 计算smaart 在硬盘健康状态中的占比
function getSMARTPercentage(){
#100 x ( 100 - 2x1 ) % = 98 %
    smartFile=$1
    smartKey=$2
    weight=$3
    percentage=$4
    scale=2

    raw_value=`getSMARTValue $smartKey $smartFile`
    if [ "$raw_value" == '' ];then
    	echo "$percentage"
    else
    	echo "scale=$scale;${percentage}*(100-${raw_value}*${weight})/100" | bc
    fi
}

function getDeviceHealth(){
	smarfile=$1
	deviceHealth=100


	## 计算硬盘已经坏了的扇区
	smartKey='Reallocated_Sector_Ct'
	weight=1
	deviceHealth=`getSMARTPercentage $smarfile $smartKey $weight $deviceHealth`


	## 寻道错误率
	smartKey='Seek_Error_Rate'
	weight=0.5
	deviceHealth=`getSMARTPercentage $smarfile $smartKey $weight $deviceHealth`



	## Spin Retry Count SMART 参数表示旋转启动尝试的重试次数
	smartKey='Spin_Retry_Count'
	weight=3
	deviceHealth=`getSMARTPercentage $smarfile $smartKey $weight $deviceHealth`



	## 重新分配事件计数SMART 参数表示重新映射操作的计数（将数据从坏扇区传输到特殊的保留磁盘区域 - 备用区域）
	smartKey='Reallocated_Event_Count'
	weight=0.6
	deviceHealth=`getSMARTPercentage $smarfile $smartKey $weight $deviceHealth`


	## Current Pending Sector Count 的增加可能意味着磁盘驱动器上有不稳定的扇区。如果待处理扇区的数量随时间增加或收到来自 SMART 扫描的警告/错误，则该更换磁盘驱动器了
	smartKey='Current_Pending_Sector'
	weight=0.6
	deviceHealth=`getSMARTPercentage $smarfile $smartKey $weight $deviceHealth`

	#不可纠正扇区数
	smartKey='Offline_Uncorrectable'
	weight=1
	deviceHealth=`getSMARTPercentage $smarfile $smartKey $weight $deviceHealth`

	echo "$deviceHealth"

}